/*
 * Copyright 2013-2018 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.example.springboot_demo.demos.web.user_work.Controller;

import com.example.springboot_demo.Common.Result;
import com.example.springboot_demo.demos.web.user_work.pojo.User;
import com.example.springboot_demo.demos.web.user_work.Server.UserServer;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;
import java.util.List;

/**
 * @author <a href="mailto:chenxilzx1@gmail.com">theonefx</a>
 */
@Api(tags = "用户接口")
@RestController
@RequestMapping("/api/user")
public class UserController {

    @Autowired
    private UserServer userServer;

    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping
    @ApiOperation("获取全部用户")
    public Result users() {
        List<User> userInfo = userServer.getUserInfos();
        return Result.success(userInfo);
    }

    @GetMapping("/{id}")
    @ApiOperation("查询用户信息")
    public Result userInfo(@PathVariable Integer id) {
        User userById = userServer.getUserById(id);
        //设置key
        String key = "user_" + userById.getId();
        ValueOperations valueOperations = redisTemplate.opsForValue();

        //查询redis是否存在
        ObjectMapper objectMapper = new ObjectMapper();
        String value = (String)valueOperations.get(key);
        if (value != null){
            try {
               return Result.success(objectMapper.readValue(value,User.class));
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        valueOperations.set(key,userById);
        return Result.success(userById);
    }
}
